<?php

namespace app\admin\model\department;

use think\Exception;
use think\Model;

class Article extends Model
{
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';


    protected static function init()
    {
        //默认新增创建者为管理员
        self::afterInsert(function ($row) {
            $model = new \app\admin\model\department\ArticleUser;
            $data = [
                "article_id" => $row['id'],
                "user_id" => $row['create_uid']
            ];
            $model->save($data);
            $model->weigh = $model->id;
            $model->is_auth = 1;
            $model->save();
        });
        //负责人为作者的第一个
//        self::beforeInsert(function ($row) {
//            if (!empty($row['author'])) {
//                $author = explode(",", $row['author']);
//                if (!empty($author)) {
//                    $row['first_author'] = $author[0];
//                }
//            }
//        });
        self::beforeUpdate(function ($row) {
            if (!empty($row['author'])) {
                $author = explode(",", $row['author']);
                if (!empty($author)) {
                    $row['first_author'] = $author[0];
                }
            }
        });
    }


    public function createuser()
    {
        return $this->belongsTo('app\admin\model\Admin', 'create_uid', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function grouping()
    {
        return $this->belongsTo('Grouping', 'grouping_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function department()
    {
        return $this->belongsTo('app\admin\model\department\Department', 'department_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function position()
    {
        return $this->belongsTo('app\admin\model\department\Position', 'position_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function type()
    {
        return $this->belongsTo('app\admin\model\department\Type', 'type_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function file()
    {
        return $this->hasMany('ArticleFile', 'id', 'article_id');
    }

}
